package com.app.micaihu.videoplayer;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;

/**
 * 监听重力感应器的工具类
 * Created by linkai on 2017/1/8.
 */
public class JCScreenSwitchUtils implements SensorEventListener {
    private volatile static JCScreenSwitchUtils mInstance;


    SensorManager sensorManager;
    Sensor accelerometerSensor;
    private Activity mActivity;
    // 屏幕方向
    private int direction;//0 横屏  1 竖屏  2 反转横屏  3反转竖屏
    private boolean isUnregister;//是否注册
    private JCVideoPlayer jcVideoPlayer;//监听的播放器


    /**
     * 返回ScreenSwitchUtils单例
     **/
    public static JCScreenSwitchUtils init(Context context) {
        if (mInstance == null) {
            synchronized (JCScreenSwitchUtils.class) {
                if (mInstance == null) {
                    mInstance = new JCScreenSwitchUtils(context);
                }
            }
        }
        return mInstance;
    }

    private JCScreenSwitchUtils(Context context) {
        // 注册重力感应器,监听屏幕旋转
        if (context == null) {
            return;
        }
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }

    /**
     * 开始监听
     */
    public void start(Activity activity, JCVideoPlayer jcVideoPlayer) {
        this.jcVideoPlayer = jcVideoPlayer;
        this.mActivity = activity;
        if (activity == null || sensorManager == null) {
            return;
        }
        if (!this.isUnregister) {
            int screenchange = -1;
            try {
                screenchange = Settings.System.getInt(activity.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
            }
//            1表示已开启 重力感应
//            0表示未开启 重力感应
            if (screenchange == 0) {
                return;
            }
            //如果当前已经注册了 则不再监听
            try {
                sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);
            } catch (Exception e) {
                e.printStackTrace();
            }
            isUnregister = true;
        }
    }

    /**
     * 停止监听
     */
    public void stop() {
        if (sensorManager == null || !isUnregister) {
            //如果没有注册则返回
            return;
        }
        //如果当前处于监听状态 则取消监听
        try {
            sensorManager.unregisterListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        isUnregister = false;
    }

    /**
     * 屏幕反转操作
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //0 横屏  1 竖屏  2 反转横屏  3反转竖屏

            switch (msg.what) {
                case 0:
                    int orientation = msg.arg1;
                    if (direction != 2 && orientation > 45 && orientation < 135) {
                        direction = 2;
                        //当前不为横屏的话则打开横屏
                        if (JCVideoPlayerManager.getCurrentJcvd() != null
//                                && JCVideoPlayerManager.getCurrentJcvd().currentScreen != JCVideoPlayer.SCREEN_WINDOW_FULLSCREEN
                                && (System.currentTimeMillis() - JCVideoPlayer.lastAutoFullscreenTime) > 3000) {
                            JCVideoPlayerManager.getCurrentJcvd().autoFullscreen(true);
                            JCVideoPlayer.lastAutoFullscreenTime = System.currentTimeMillis();
                        }

                    } else if (direction != 3 && orientation > 135 && orientation < 225) {
                        direction = 3;
                        //如果是全屏则退出全屏
                        if(JCVideoPlayerManager.getCurrentJcvd() != null
                            && JCVideoPlayerManager.getCurrentJcvd().currentScreen == JCVideoPlayer.SCREEN_WINDOW_FULLSCREEN){
                            JCVideoPlayerManager.getCurrentJcvd().backPress();
                        }

                    } else if (direction != 0 && orientation > 225 && orientation < 315) {
                        direction = 0;
                        //当前不为横屏的话则打开横屏
                        if (JCVideoPlayerManager.getCurrentJcvd() != null
                                && (System.currentTimeMillis() - JCVideoPlayer.lastAutoFullscreenTime) > 3000) {
                            JCVideoPlayerManager.getCurrentJcvd().autoFullscreen(false);
                            JCVideoPlayer.lastAutoFullscreenTime = System.currentTimeMillis();
                        }

                    } else if (direction != 1 && ((orientation > 315 && orientation < 360) || (orientation > 0 && orientation < 45))) {
                        direction = 1;
                        if(JCVideoPlayerManager.getCurrentJcvd()!= null && JCVideoPlayerManager.getCurrentJcvd().currentScreen == JCVideoPlayer.SCREEN_WINDOW_FULLSCREEN){
                            JCVideoPlayerManager.getCurrentJcvd().backPress();
                        }
                    }
                    break;
                default:
                    break;
            }

        }

        ;
    };

    /**
     * 监听屏幕方向
     *
     * @param event
     */
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (!isUnregister || !JCMediaManager.isUseing) {
            //如果当前没有监听状态 则不做监听
            //如果当前没有播放视频也不做监听
            return;
        }
        final float X = event.values[SensorManager.DATA_X];
        float Y = event.values[SensorManager.DATA_Y];
        float Z = event.values[SensorManager.DATA_Z];
        int orientation = -1;
        float magnitude = X * X + Y * Y;
        // Don't trust the angle if the magnitude is small compared to the y
        // value
        if (magnitude * 4 >= Z * Z) {
            // 屏幕旋转时
            float OneEightyOverPi = 57.29577957855f;
            float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
            orientation = 90 - (int) Math.round(angle);
            // normalize to 0 - 359 range
            while (orientation >= 360) {
                orientation -= 360;
            }
            while (orientation < 0) {
                orientation += 360;
            }
        }
        if (mHandler != null) {
            mHandler.obtainMessage(0, orientation, 0).sendToTarget();
        }
    }

//    @Override
//    public void onSensorChanged(SensorEvent event) {//可以得到传感器实时测量出来的变化值
//        final float x = event.values[SensorManager.DATA_X];
//        float y = event.values[SensorManager.DATA_Y];
//        float z = event.values[SensorManager.DATA_Z];
//        LogUtils.i("onSensorChanged-----------"+x+"---------"+y);
//        //过滤掉用力过猛会有一个反向的大数值
//        if (((x > -15 && x < -10) || (x < 15 && x > 10)) && Math.abs(y) < 1.5) {
//            LogUtils.i("进入if----");
//            if ((System.currentTimeMillis() - JCVideoPlayer.lastAutoFullscreenTime) > 2000) {
//                Log.i("debug", "JCVideoPlayerManager.getCurrentJcvd()---" + JCVideoPlayerManager.getCurrentJcvd());
//                if (JCVideoPlayerManager.getCurrentJcvd() != null) {
//                    JCVideoPlayerManager.getCurrentJcvd().autoFullscreen(x);
//                }
//                JCVideoPlayer.lastAutoFullscreenTime = System.currentTimeMillis();
//            }
//        }
//    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }


}
